package com.sjtu.servlet;

import com.sjtu.bean.UserBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    public void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String obj = request.getParameter("obj");
        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(obj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        try {
            String username = jsonObj.getString("username");
            String password = jsonObj.getString("password");
//            System.out.println("aaa"+username+password);
            UserBean user = UserBean.getUser(username, password);
            if (user == null) {
                writer.write("Wrong combination of username and password");
            } else {
                boolean isAdmin = user.isAdmin();
                JSONObject jsonRes = new JSONObject();
                jsonRes.put("name", user.getName());
                jsonRes.put("id", user.getId());
                jsonRes.put("isAdmin", isAdmin);
                System.out.println("here:" + jsonRes.toString());
                writer.write(jsonRes.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    }
}
